package com.acme.bankapp.domain.bank;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.exceptions.ClientExistsException;
import com.acme.bankapp.service.bank.BankAplication;
import com.acme.bankapp.service.bank.BankService;
import com.acme.bankapp.service.bank.ClientRegistrationListener;

public class Bank implements Serializable {

        private String name;
		private List<Client> clients = new ArrayList<Client> ();
        private List<ClientRegistrationListener> listeners =
                        new ArrayList<ClientRegistrationListener>();
        
        ClientRegistrationListener debugListener = new DebugListener();
        
        public List<Client> getClients() {
                return clients;
        }
        
        public Bank(String name) {
        	
        	this.name = name;
            listeners.add( new ClientRegistrationListener() {
                    @Override
                    public void onClientAdded(Bank b, Client c) {
                            System.out.println("\nClient " + c.getName() + " was added");
                    }
            });
            
            listeners.add(new ClientRegistrationListener() {
                    @Override
                    public void onClientAdded(Bank b, Client c) {
                            System.out.println("Notification email for client " + c.getName() + " was sent");
                    }
            });
            listeners.add(debugListener);
            
            listeners.add(new ClientRegistrationListener() {
                @Override
                public void onClientAdded(Bank b, Client c) throws IOException {
                    BankService.saveBank(b, BankAplication.dataBaseFile);
                	System.out.println("Bank DataBase was saved");
                }
            });
        }
        
        class DebugListener implements ClientRegistrationListener {
                @Override
                public void onClientAdded(Bank b, Client c) {
                        System.out.println("Debug " + c.getName() + " " + java.util.Calendar.getInstance().getTime());
                }
        }
        
    	public void addClient(Client client) throws ClientExistsException, IOException {
    		for (Client c : clients) {
    			if (c.getName().equals(client.getName())) {
    				throw new ClientExistsException(
    					"Client with name " + client.getName() + " already exists");
                }
    		}
    		
    		clients.add(client);
    		for (ClientRegistrationListener listener : listeners)
    			listener.onClientAdded(this, client);
    	}

		public String getName() {
			return name;
		}

}
